package org.linlinjava.litemall.wx.util;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.mgt.DefaultSecurityManager;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.subject.Subject;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.util.AntPathMatcher;
import org.springframework.util.PathMatcher;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Configuration
@WebFilter(urlPatterns = "/wx/**", filterName = "merchantHeaderFilter")
@Order(2)
public class MerchantHeaderFilter implements Filter  {
    private final Log log = LogFactory.getLog(MerchantHeaderFilter.class);
    public static final String MERCHANT_PARAM_KEY = "X-Litemall-mchtid";



    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        log.info("MerchantHeaderFilter init...");
        SecurityManager security = new DefaultSecurityManager();
        SecurityUtils.setSecurityManager(security);
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) servletRequest;
        HttpServletResponse resp = (HttpServletResponse) servletResponse;

        resp.setCharacterEncoding("UTF-8");

        String  url  = req.getServletPath();

        PathMatcher matcher = new AntPathMatcher();
        if( matcher.match("/wx/**", url) && !matcher.match("/wx/storage/**", url)
            && !req.getMethod().equals("OPTIONS")) {
            String merchantId = req.getHeader(MERCHANT_PARAM_KEY);      // 商户id
            //log.info("merchantId");
            //log.info(merchantId);

            if (StringUtils.isNotBlank(merchantId)) {

                Subject subject = SecurityUtils.getSubject();
                subject.getSession().setAttribute(MERCHANT_PARAM_KEY, merchantId);
            }

            if (merchantId == null) {
                log.error("非法请求:无效的商户id信息");
               // throw new IllegalArgumentException("非法请求:无效的商户id信息");
            }
        }

        filterChain.doFilter(servletRequest, servletResponse);
    }

    @Override
    public void destroy() {

    }
}
